<template>
  <div class="app-container">
    <div class="filter-container clearfix">
      <el-button v-if="checkPermission(permissionRoles.vip_service_add)" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">添加配置</el-button>
    </div>
    <el-table ref="table" v-loading="listLoading" :data="list" border stripe style="width: 100%;" height="670">
      <el-table-column label="配置ID" prop="id" width="60px" align="center" fixed></el-table-column>
      <el-table-column label="配置备注" prop="notes" width="100px" align="center" fixed></el-table-column>
      <el-table-column label="渠道" prop="cidname" width="90px" align="center" fixed></el-table-column>
      <!-- <el-table-column label="发行渠道" prop="cpname" width="90px" align="center" fixed></el-table-column>
      <el-table-column label="大区" prop="srid" width="90px" align="center" fixed></el-table-column> -->
      <el-table-column label="开服天数" prop="open_days" width="70px" align="center"></el-table-column>
      <el-table-column label="等级" prop="level" width="50px" align="center"></el-table-column>
      <el-table-column label="总充值金额" prop="amount" width="80px" align="center"></el-table-column>
      <el-table-column label="文案" width="150px" align="center">
        <template slot-scope="{row}">
          <span v-if="row.content === null">{{ row.content }}</span>
          <span v-else-if="row.content.length < 20">{{ row.content }}</span>
          <el-popover v-else trigger="hover" placement="top">
            <p>{{ row.content }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ row.content | sliceFilter }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="二维码" prop="qrcode" width="100px" align="center">
        <template slot-scope="{row}">
          <el-image style="width: 50px; height: 50px" :src="`${row.qrcode}`" fit="fit"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="联系名" prop="contact" width="90px" align="center"></el-table-column>
      <el-table-column label="联系方式" prop="wechat" width="90px" align="center"></el-table-column>
      <el-table-column label="弹窗" width="70px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.pop | statusFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="红点" width="70px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.red | statusFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="附件内容" prop="items_str" width="269px" align="center"></el-table-column>
      <el-table-column label="更新时间" prop="update_dt" width="140px" align="center"></el-table-column>
      <el-table-column label="开关" width="70px" align="center">
        <template slot-scope="{row}">
          <el-switch
            v-model="row.status"
            active-value="1"
            inactive-value="0"
            @change="handleSwitch(row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作人" prop="create_user" width="60px" align="center"></el-table-column>
      <el-table-column label="操作" width="90px" align="center" fixed="right">
        <template slot-scope="{row}">
          <el-button v-if="checkPermission(permissionRoles.vip_service_edit)" type="text" size="small" title="编辑" @click="handleEdit(row)">修改</el-button>
          <el-button v-if="checkPermission(permissionRoles.vip_service_del)" type="text" size="small" title="删除" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" :title="textMap[dialogType]" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="渠道" prop="cid">
          <el-select v-model="dataForm.cid" class="defaut-input" clearable>
            <el-option
              v-for="item in channelList"
              :key="item.cid"
              :label="item.name + ' (' + item.cid + ')'"
              :value="item.cid"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="发行渠道" prop="cpid">
          <el-select v-model="dataForm.cpid" class="defaut-input" clearable>
            <el-option
              v-for="item in cpList"
              :key="item.cpid"
              :label="item.cpname + ' (' + item.cpid + ')'"
              :value="item.cpid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="大区选择" prop="srid">
          <el-select v-model="dataForm.srid" filterable class="defaut-input" clearable>
            <el-option
              v-for="item in serverRegionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="配置备注" prop="notes">
          <el-input v-model="dataForm.notes" class="defaut-input" placeholder="填写配置备注" />
        </el-form-item>
        <el-form-item label="开服天数">
          <el-input v-model="dataForm.open_days" class="defaut-input" placeholder="填写开服天数" />
        </el-form-item>
        <el-form-item label="角色等级">
          <el-input v-model="dataForm.level" class="defaut-input" placeholder="填写角色等级" />
        </el-form-item>
        <el-form-item label="总充值金额">
          <el-input v-model="dataForm.amount" class="defaut-input" placeholder="总充值金额" />
        </el-form-item>
        <el-form-item label="联系名">
          <el-input v-model="dataForm.contact" class="defaut-input" placeholder="QQ或者微信" />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="dataForm.wechat" class="defaut-input" placeholder="QQ号或者微信号" />
        </el-form-item>
        <el-form-item label="二维码">
          <el-input v-model="dataForm.qrcode" class="defaut-input" placeholder="填写二维码连接地址" />
        </el-form-item>
        <el-form-item label="弹窗" prop="pop">
          <el-select v-model="dataForm.pop" class="defaut-input" clearable>
            <el-option label="无" value="10000" />
            <el-option label="每次" value="0" />
            <el-option label="每天" value="1" />
            <el-option label="每3天" value="3" />
            <el-option label="每7天" value="7" />
          </el-select>
        </el-form-item>
        <el-form-item label="红点" prop="red">
          <el-select v-model="dataForm.red" class="defaut-input" clearable>
            <el-option label="无" value="10000" />
            <el-option label="每次" value="0" />
            <el-option label="每天" value="1" />
            <el-option label="每3天" value="3" />
            <el-option label="每7天" value="7" />
          </el-select>
        </el-form-item>

        <el-form-item label="附件内容">
          <el-row>
            <el-col :md="3"><el-button type="primary" class="add" icon="el-icon-plus" @click="productAdd">新增</el-button></el-col>
          </el-row>
          <el-row
            v-for="(item, index) in dataForm.items"
            :key="index"
            class="mt-5"
            :gutter="12"
          >
            <el-col :md="6">
              <el-select v-model="item.id" clearable filterable placeholder="请选择物品">
                <el-option
                  v-for="p in products"
                  :key="p.id"
                  :label="p.desc"
                  :value="p.id"
                />
              </el-select>
            </el-col>
            <el-col :md="8"><el-input v-model="item.num" placeholder="数量" /></el-col>
            <el-col :md="4"><el-button type="danger" icon="el-icon-delete" @click.prevent="remove(item)" /></el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="显示文案">
          <quillEditor ref="myQuillEditor" v-model="dataForm.content" class="ql-editor"></quillEditor>
        </el-form-item>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import checkPermission from '@/utils/permission' // 权限判断函数
import waves from '@/directive/waves' // 实现点击波浪纹
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { objectMerge, deepClone } from '@/utils'
import quillEditor from '@/components/QuillEditor'
import { getAllChannel, getServerRegionList, getChannelPackageList } from '@/api/ops'
import { getItemConfig } from '@/api/config'
import { handleVipService, getVipServiceList, deleteVipService } from '@/api/operator'

const defaultItem = {
  id: '',
  notes: '',
  cid: '',
  cpid: '',
  srid: '',
  open_days: '',
  level: '',
  amount: '',
  qrcode: '',
  wechat: '',
  contact: '',
  pop: '10000',
  red: '10000',
  content: '',
  items: [{
    id: '',
    num: ''
  }]
}
export default {
  name: 'VipService',
  components: { Pagination, quillEditor },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        10000: '无',
        0: '每次',
        1: '每天',
        3: '每3天',
        7: '每7天'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      header: {
        Authorization: this.$store.state.user.token
      },
      permissionRoles: this.$store.state.user.permissionRoles,
      servicePicUrl: process.env.VUE_APP_SERVICE_PIC_URL,
      cpList: [],
      fileList: [],
      products: [],
      serverRegionList: [],
      channelList: [],
      list: [],
      total: 0,
      loading: false,
      listLoading: false,
      dataForm: Object.assign({}, defaultItem),
      rules: {
        cid: [{ required: true, message: '请选择渠道', trigger: 'blur' }],
        // cpid: [{ required: true, message: '请选择发行渠道', trigger: 'blur' }],
        // srid: [{ required: true, message: '请选择大区', trigger: 'blur' }],
        notes: [{ required: true, message: '请填写配置备注', trigger: 'blur' }]
      },
      listQuery: {
        page: 1,
        limit: 200
      },
      dialogType: 'new',
      textMap: {
        new: '添加',
        edit: '编辑'
      },
      dialogVisible: false
    }
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill
    }
  },
  created() {
    this.getList()
    this.getServerRegionList()
    this.getAllChannelList()
  },
  methods: {
    checkPermission,
    async getList() {
      const query = objectMerge(this.searchForm, this.listQuery)
      this.listLoading = true
      const res = await getVipServiceList(query)
      this.listLoading = false
      this.list = res.data.items
      this.total = res.data.total
    },
    async getServerRegionList() {
      const res = await getServerRegionList()
      this.serverRegionList = res.data
    },
    async getAllChannelList() {
      const res = await getAllChannel()
      this.channelList = res.data
    },
    async getItemConfig() {
      const res = await getItemConfig()
      this.products = res.data.items
    },
    handleFilter() {
      this.getList()
    },
    async getCpList() {
      const res = await getChannelPackageList()
      this.cpList = res.data.items
    },
    handleAdd() {
      this.fileList = []
      this.getCpList()
      this.getItemConfig()
      this.dialogType = 'new'
      this.dataForm = Object.assign({}, defaultItem)
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEdit(row) {
      if (row.items === null) row.items = ''
      if (Array.isArray(row.items) === false) {
        if (row.items === '') {
          row.items = [{ id: '', num: '' }]
        } else {
          const items = JSON.parse(row.items)
          const a = []
          for (let i = 0; i < items.length; i++) {
            const o = { id: '', num: '' }
            o.id = items[i].itemId
            o.num = items[i].num
            a[i] = o
          }
          row.items = a
        }
      }
      this.getItemConfig()
      this.getCpList()
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.dataForm = deepClone(row)
      // this.dataForm.srid = Number(this.dataForm.srid)
      console.log(this.dataForm)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          handleVipService(this.dataForm).then(response => {
            if (response.status) {
              this.dialogVisible = false
              this.getList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('你确定要删除此行数据吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteVipService(row.id)
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(err => { console.error(err) })
    },
    handleSwitch(row) {
      this.$confirm('你确定要操作游戏显示VIP客服吗?', '限制显示VIP客服', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          handleVipService({ status: row.status, id: row.id }).then(response => {
            if (response.status) {
              this.dialogVisible = false
              this.getList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.message.error(response.message)
            }
          })
        })
        .catch(err => { console.error(err) })
    },
    productAdd(row) {
      if (this.dataForm.items.length === 6) {
        return
      }
      this.dataForm.items.push({
        id: '',
        num: ''
      })
    },
    remove(row) {
      var index = this.dataForm.items.indexOf(row)
      if (index !== -1) {
        this.dataForm.items.splice(index, 1)
      }
    }
  }
}
</script>
